package com.kun.reflection.demo02_memoryAnalysis;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

// Class对象的作用
public class Test05_ClassUse {


    @Test
    public void test01() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 1. 使用Class对象创建对象
        //1.1 无参构造
        Class personClass = Class.forName("com.kun.reflection.demo02_memoryAnalysis.Person");
        Person person = (Person) personClass.newInstance();
        System.out.println(person);

        //1.2 有参构造
        Constructor constructor = personClass.getConstructor(String.class, int.class);
        Person person1 = (Person) constructor.newInstance("张三", 20);
        System.out.println(person1);

        //2. 使用Class对象使用方法
        Method setName = personClass.getMethod("setName", String.class);
        setName.invoke(person, "李四");
        System.out.println(person);

        //3. 使用CLass对象操作属性，由于权限，需要关闭安全检查
        Field ageField = personClass.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(person, 25);
        System.out.println(person);

    }
}
